/*
 * Created on 20 �.�. 2004
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package com.softplus.carrefour.hd.frontend.servlet.process;

import com.epro.standard.frontend.datasetup.MessageManager;
import com.epro.standard.frontend.servlet.EproServlet;

import com.softplus.carrefour.CFException;
import com.softplus.carrefour.hd.CFHDSystem;
import com.softplus.carrefour.hd.bltier.db.HibernateUtil;
import com.softplus.carrefour.hd.bltier.entity.CfhdCaseDetail;
import com.softplus.carrefour.hd.bltier.entity.CfhdCaseDetailPK;
import com.softplus.carrefour.hd.bltier.entity.CfhdCaseDoc;
import com.softplus.carrefour.hd.bltier.entity.CfhdCaseHead;
import com.softplus.carrefour.hd.bltier.entity.CfhdCaseKeyword;
import com.softplus.carrefour.hd.bltier.entity.RoutePath;
import com.softplus.carrefour.hd.bltier.entity.UserAccount;
import com.softplus.carrefour.hd.bltier.pc.CCaseDetailManage;
import com.softplus.carrefour.hd.bltier.pc.CCaseDocManage;
import com.softplus.carrefour.hd.bltier.pc.CCaseHeadManage;
import com.softplus.carrefour.hd.bltier.pc.CCaseKeywordManage;
import com.softplus.carrefour.hd.bltier.pc.ICaseDetailControl;
import com.softplus.carrefour.hd.bltier.pc.ICaseDocControl;
import com.softplus.carrefour.hd.bltier.pc.ICaseHeadControl;
import com.softplus.carrefour.hd.bltier.pc.ICaseKeywordControl;
import com.softplus.carrefour.hd.bltier.util.DateUtil;
import com.softplus.carrefour.hd.bltier.util.httpUpload;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;

import java.math.BigDecimal;

import java.sql.Connection;
import java.sql.SQLException;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.Hashtable;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileUploadException;


/**
 * @author Nancy
 */
public class CFHDPC05_2 extends EproServlet {
    public void doPost(HttpServletRequest request, 
                       HttpServletResponse response) throws ServletException, 
                                                            IOException {
        //======================Define Variable======================>

        //=================Select action for Managing==================>		
        this.insertData(request, response);
    }

    //	-------------------------------------------------------------------------------------------------->
    //																										\\
    //													  INSERT											\\
    //																										\\
    //	--------------------------------------------------------------------------------------------------->	

    public void insertData(HttpServletRequest request, 
                           HttpServletResponse response) throws ServletException, 
                                                                IOException {
        System.out.println("^^^^^^^^servlet^^^insert^^^^^^^^^^^^");
        HttpSession session = request.getSession(true);
        /*		  EproServletUtil	servletUtil	= new EproServletUtil(request) ;*/

        //	======================Define redirect page==================>
        String parameterLink = 
            ""; //= "&fromDateDash="+fromDate+"&toDateDash="+toDate ;
        String URL = "../PC/CFHDPCMT05_2.jsp"; //"../PC/CFHDPCMT02.jsp"; //
        String successLink = URL + "?check=true" + parameterLink;
        String unsuccessLink = URL + "?check=false" + parameterLink;
        Hashtable hash = new Hashtable(); // = upload.getFormFields();
        String CONTENT_TYPE = "text/html; charset=TIS-620";
        response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();
        try {

            //	======================Define Variable======================>
            UserAccount userVO = 
                (UserAccount)request.getSession().getAttribute("userVO"); //"kunlaporn_c";
            // for Doc
            httpUpload upload; //initial value
            // ======= Define object for Doc ======== //
            ICaseDocControl docManage = 
                (CCaseDocManage)CFHDSystem.getControlClass("CASE_DOC");
            upload = docManage.setCaseDoc(request);
            System.out.println(upload.getFileSize() + "...................." + 
                               upload.getMaxFileSize());
            if (upload.getFileSize() < upload.getMaxFileSize()) {
                hash = upload.getFormFields();
                // for Head
                String userID = 
                    userVO.getUserId() == null ? "" : userVO.getUserId(); //"kunlaporn_c";//request.getParameter("uid");
                System.out.println("......" + userID + "......");
                String caseNo = ""; //initial value
                String caseStatus = 
                    (String)hash.get("CASESTATUS") == null ? "" : 
                    (String)hash.get("CASESTATUS");
                String reqName = 
                    (String)hash.get("REQNAME") == null ? "" : (String)hash.get("REQNAME");
                String telephone = 
                    (String)hash.get("TELEPHONE") == null ? "" : (String)hash.get("TELEPHONE");
                String fax = 
                    (String)hash.get("FAX") == null ? "" : (String)hash.get("FAX");
                String openDate = 
                    (String)hash.get("OPENDATE") == null ? "" : (String)hash.get("OPENDATE");
                String closedDate = 
                    (String)hash.get("CLOSEDDATE") == null ? "" : 
                    (String)hash.get("CLOSEDDATE");
                //String 		reporter			= (String)hash.get("REPORTER")==null? "":(String)hash.get("REPORTER");
                String countryID = 
                    userVO.getCountry().getCountryId() == null ? "" : 
                    userVO.getCountry().getCountryId();
                String site = 
                    (String)hash.get("SITE") == null ? "" : (String)hash.get("SITE");
                String system = 
                    (String)hash.get("SYSTEM") == null ? "" : (String)hash.get("SYSTEM");
                String module = 
                    (String)hash.get("MODULE") == null ? "" : (String)hash.get("MODULE");
                String aldata = 
                    (String)hash.get("ALDATA") == null ? "" : (String)hash.get("ALDATA");
                String gold = 
                    (String)hash.get("GOLDVERSION") == null ? "" : (String)hash.get("GOLDVERSION");
                String environment = 
                    (String)hash.get("ENVIRONMENT") == null ? "" : 
                    (String)hash.get("ENVIRONMENT");
                String screen = 
                    (String)hash.get("SCREEN") == null ? "" : (String)hash.get("SCREEN");
                String caseType = 
                    (String)hash.get("CASETYPE") == null ? "" : (String)hash.get("CASETYPE");
                Integer severity = 
                    (Integer.valueOf((String)hash.get("SEVERITY"))) == null ? 
                    new Integer(0) : 
                    (Integer.valueOf((String)hash.get("SEVERITY")));
                String subject = 
                    (String)hash.get("SUBJECT") == null ? "" : (String)hash.get("SUBJECT");
                String rptBy = 
                    (String)hash.get("RPTBY") == null ? "" : (String)hash.get("RPTBY");
                String DWNumber = 
                    (String)hash.get("DWNUMBER") == null ? "" : (String)hash.get("DWNUMBER");
                // for Detail
                String detail = 
                    (String)hash.get("DETAIL") == null ? "" : (String)hash.get("DETAIL");
                String detailSeq = "0"; //initial value
                // for keyword
                String keyword1 = 
                    (String)hash.get("KEYWORD1") == null ? "" : (String)hash.get("KEYWORD1");
                String keyword2 = 
                    (String)hash.get("KEYWORD2") == null ? "" : (String)hash.get("KEYWORD2");
                String keyword3 = 
                    (String)hash.get("KEYWORD3") == null ? "" : (String)hash.get("KEYWORD3");
                // for doc
                String attach = 
                    upload.getFileName() == null ? "" : upload.getFileName(); //(String)hash.get("ATT_FILE_NAME");//request.getParameter("attach");
                String description = 
                    (String)hash.get("ATT_DESC") == null ? "" : 
                    (String)hash.get("ATT_DESC"); //request.getParameter("description");
                SimpleDateFormat dateDispFormat = 
                    new SimpleDateFormat("d/M/yyyy", Locale.US);
                SimpleDateFormat dateInputFormat = 
                    new SimpleDateFormat("d/MM/yyyy", Locale.US);
                String finishDate = 
                    (String)hash.get("FINISHDATE") != null ? (String)hash.get("FINISHDATE") : 
                    dateDispFormat.format(new Date());
                Date dateToApply = null;

                if (!finishDate.equals("")) {
                    try {
                        dateToApply = dateInputFormat.parse(finishDate);
                    } catch (ParseException e) {
                    }
                }

                //	======================Define Object======================>
                ICaseHeadControl headManage = 
                    (CCaseHeadManage)CFHDSystem.getControlClass("CASE_HEAD");
                ICaseKeywordControl keyManage = 
                    (CCaseKeywordManage)CFHDSystem.getControlClass("CASE_KEYWORD");
                ICaseDetailControl detailManage = 
                    (CCaseDetailManage)CFHDSystem.getControlClass("CASE_DETAIL");
                CfhdCaseHead headEntity = new CfhdCaseHead();
                CfhdCaseDetail detailEntity = new CfhdCaseDetail();
                CfhdCaseDetail detail2Entity = new CfhdCaseDetail();
                CfhdCaseKeyword keyEntity = new CfhdCaseKeyword();
                CfhdCaseDoc docEntity = new CfhdCaseDoc();
                System.out.println("..................................its size can be upload.........................2");

                //	======================Set Property of entity Object===========> 
                // Head Control
                //PKs
                headEntity.setUserId(userID);
                headEntity.setCaseId("");
                //FKs
                headEntity.setCfhdEnvironment(environment);
                headEntity.setCfhdSystem(system);
                headEntity.setCfhdModule(module);
                //Attributes
                headEntity.setCaseStatus(CfhdCaseHead.STATUS_VALIDATED);
                headEntity.setReqName(reqName);
                headEntity.setReqTel(telephone);
                headEntity.setReqFax(fax);
                headEntity.setOpenCaseDate(DateUtil.getLocalDate(userID));
                headEntity.setReportedBy(rptBy);
                headEntity.setDwNumber(DWNumber);
                //headEntity.setCloseCaseDate(closedDate);
                headEntity.setCountryId(userVO.getCountry().getCountryId());
                headEntity.setAlDataNo(aldata);
                headEntity.setGoldVersion(gold);
                headEntity.setScreenName(screen);
                headEntity.setCaseType(caseType);
                headEntity.setOriginCaseType(caseType);
                headEntity.setSeverity(severity);
                headEntity.setOriginSeverity(severity);
                headEntity.setSubject(subject);
                headEntity.setStoreId(site);
                headEntity.setRouteDirection(RoutePath.ESCALATE);
                //headEntity.setAutoEscalateStatus(true);
                headEntity.setOpenStatus(true);
                headEntity.setCredBy(userID);
                //headEntity.setCredDate(DateUtil.getLocalDate(userID));
                headEntity.setUpdBy(userID);
                //headEntity.setUpdDate(DateUtil.getLocalDate(userID));
                //	======================Set Method for Manage================>
                caseNo = headManage.insertCfhdCaseHead(headEntity);
                System.out.println("===================Insert Head Complete ====================");
                // Keyword Control
                keyEntity.setCaseId(caseNo);
                keyEntity.setKeyFirst(keyword1);
                keyEntity.setKeySecond(keyword2);
                keyEntity.setKeyThird(keyword3);
                keyEntity.setCredBy(userID);
                keyEntity.setCredDate(DateUtil.getLocalDate(userID));
                keyEntity.setUpdBy(userID);
                keyEntity.setUpdDate(DateUtil.getLocalDate(userID));
                //	======================Set Method for Manage================>
                keyManage.insertCaseKeyWord(keyEntity);
                System.out.println("===================Insert Keyword Complete ====================");
                // Detail Control
                // sequence 1
                detailEntity.setComp_id(new CfhdCaseDetailPK(caseNo, 
                                                             new BigDecimal(0)));
                detailEntity.setUserId(userID);
                detailEntity.setCountryId(countryID);
                detailEntity.setDetDesc(detail);
                detailEntity.setDetType(CfhdCaseDetail.CASE_DETAIL);
                detailEntity.setCaseAction(CfhdCaseDetail.ACTION_INITIAL);
                //detailEntity.setCfhdErrType();
                detailEntity.setTransferFrom(userID);
                detailEntity.setTransferTo(userID);
                detailEntity.setTransferToLv("L1C");
                detailEntity.setOpenedTime(DateUtil.getLocalDate(userID));
                detailEntity.setSubmitTime(DateUtil.getLocalDate(userID));
                detailEntity.setCaseDetStatus(CfhdCaseHead.STATUS_SUBMITTED);
                //System.out.println("+++++++++++++++++++"+CfhdCaseHead.STATUS_SUBMITTED+"++"+severity+"++"+caseType+"++");
                detailEntity.setCaseDetServerity(severity);
                detailEntity.setCaseDetType(caseType);
                if (caseType.equals("P4")) {
                    detailEntity.setDateToApply(dateToApply);
                }
                detailEntity.setCredBy(userID);
                //detailEntity.setCredDate(DateUtil.getLocalDate(userID));
                detailEntity.setUpdBy(userID);
                //detailEntity.setUpdDate(DateUtil.getLocalDate(userID));
                //	======================Set Method for Manage================>
                detailSeq = detailManage.insertCfhdCaseDetail(detailEntity);
                System.out.println("===================Insert Detail 0 Complete ====================");
                // sequence 2
                detail2Entity.setComp_id(new CfhdCaseDetailPK(caseNo, 
                                                              new BigDecimal(1)));
                detail2Entity.setUserId(userID);
                detail2Entity.setCountryId(countryID);
                detail2Entity.setOpenedTime(DateUtil.getLocalDate(userID));
                detail2Entity.setCaseDetStatus(CfhdCaseHead.STATUS_VALIDATED);
                if (caseType.equals("P4")) {
                    detail2Entity.setDateToApply(dateToApply);
                }
                detail2Entity.setCredBy(userID);
                //detailEntity.setCredDate(DateUtil.getLocalDate(userID));
                detail2Entity.setUpdBy(userID);
                //detailEntity.setUpdDate(DateUtil.getLocalDate(userID));
                //						======================Set Method for Manage================>
                detailManage.insertCfhdCaseDetail(detail2Entity);
                System.out.println("===================Insert Detail 1 Complete ====================");
                // Doc Control
                System.out.println("..................." + detailSeq);
                if (!attach.equals("")) {
                    try {
                        System.out.println("===================Begin Upload ====================");
                        // Set Table Name
                        upload.setTableName("CFHD_CASE_DOC");
                        // Add primary key
                        upload.addColumnPK("CASE_ID");
                        upload.addColumnPK("CASE_DET_SEQ");
                        upload.addColumnPK("CASE_DOC_SEQ");
                        upload.addColumnPK("ATT_DESC");
                        // Set file name column
                        upload.setColumnFileName("ATT_FILE_NAME");
                        // Add Value to PK
                        upload.addValuePK("'" + caseNo + "'"); // Varchar
                        upload.addValuePK(detailSeq); // Number
                        upload.addValuePK("0"); // Number
                        upload.addValuePK("'" + (String)hash.get("ATT_DESC") + 
                                          "'"); // Varchar

                        // Set LOB Column
                        upload.setLOBColumnName("ATT_FILE");
                        // Set file is BLOB or CLOB
                        upload.setBLOB();
                        //upload.setDataUnique("'"+caseId+"',"+detSeq+","+docSeq);
                        // Set Destination is DATABASE or FILEBASE
                        upload.setDestination("DATABASE");
                        System.out.println("===================End Upload Set====================");
                        try {
                            // Set Connection
                            System.out.println("===================Begin Upload set Connection====================");
                            upload.setConnection((Connection)HibernateUtil.getConnection());
                        } catch (CFException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        try {
                            System.out.println("===================Start Upload ====================");
                            upload.upload(userID); //dho modified
                            System.out.println("===================End Upload ====================");
                        } catch (FileNotFoundException e2) {
                            // TODO Auto-generated catch block
                            e2.printStackTrace();
                        } catch (ServletException e2) {
                            // TODO Auto-generated catch block
                            e2.printStackTrace();
                        } catch (IOException e2) {
                            // TODO Auto-generated catch block
                            e2.printStackTrace();
                        } catch (SQLException e2) {
                            // TODO Auto-generated catch block
                            e2.printStackTrace();
                        }
                    } catch (FileUploadException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    System.out.println("===================Insert Doc Complete ====================");
                } // end if attach is null
                session.setAttribute("hasError", 
                                     MessageManager.getInsertSuccessString());
                out.println("<SCRIPT type='text/javascript'>");
                out.println("parent.location='/CFHD/PC/CFHDPCMT03_2.jsp';");
                out.println("</SCRIPT>");
            } // end if file size is not over
            else {
                //session.setAttribute("hasError",new CFException(new Exception(MessageManager.getUploadUnsuccessString())));
                session.setAttribute("hasError", 
                                     MessageManager.getUploadUnsuccessString());
                response.sendRedirect(unsuccessLink);
            }
            //	======================Set session for Master page Alert ========>
        } catch (CFException cfe) {
            cfe.printStackTrace();
            /*			  session.setAttribute("hasError",MessageManager.getInsertUnsuccessString()*/
            response.sendRedirect(unsuccessLink);
        } //End catch CFException
    } // end insertData()
}// end class CFHDPC05